package com.leoman.category.controller;

import com.leoman.category.entity.Category;
import com.leoman.category.service.CategoryService;
import com.leoman.category.service.impl.CategoryServiceImpl;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.post.entity.PostBase;
import com.leoman.post.service.PostBaseService;
import com.leoman.resource.service.MusicService;
import com.leoman.resource.service.StillService;
import com.leoman.resources.entity.MusicResource;
import com.leoman.resources.entity.StillResource;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import com.leoman.work.entity.Work;
import com.leoman.work.service.WorkService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/24 0024.
 */
@Controller
@RequestMapping(value = "admin/category")
public class CategoryController extends GenericEntityController<Category, Category, CategoryServiceImpl> {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    @Autowired
    private PostBaseService postBaseService;

    @Autowired
    private StillService stillService;

    @Autowired
    private MusicService musicService;

    @Autowired
    private WorkService workService;

    /**
     * 作品集分类列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "category/list";
    }

    /**
     * 查询作品集分类列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<Category> page = categoryService.page(null, pageNum, length);
            List<Work> workList;
            for (Category category : page.getContent()) {
                if (StringUtils.isNotEmpty(category.getUrl())) {
                    category.setUrl(ImageUtil.clearUploadUrl(category.getUrl()));
                }

                // 作品集分类下的数量
                workList = workService.iFindList(category.getId());
                category.setCount((long) (workList != null ? workList.size() : 0));
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 编辑保存作品集分类
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    private Integer edit(String name,
                         Long categoryId,
                         Integer type,
                         @RequestParam(value = "imageFile", required = false) MultipartFile file) {

        name = sensitiveWordsService.replaceWord(name);
        //categoryService.saveEdit(request, name, categoryId, type, file);
        Category category;
        if (categoryId == null) {
            category = new Category();
        } else {
            category = categoryService.queryByPK(categoryId);
        }

        //MultipartFile multipartFile = file;
        if (null != file) {
            FileBo fileBo = new FileBo();
            try {
                fileBo = FileUtil.save(file, true);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (fileBo != null) {
                category.setUrl(fileBo.getPath());
                category.setSuolue(fileBo.getSuoluePath());
            }
        }

        category.setType(type);
        category.setName(name);
        category.setUpdateDate(System.currentTimeMillis());

        if (null == categoryId) {
            Category tempCategory = categoryService.getShowTurn(0);

            if (null == tempCategory) {
                category.setShowTurn(1);
            } else {
                category.setShowTurn(tempCategory.getShowTurn() + 1);
            }

            categoryService.update(category);
        }

        categoryService.save(category);
        return 1;
    }

    /**
     * 帖子分类列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexPost")
    public String indexPost() {
        return "category/listPost";
    }

    /**
     * 查询帖子分类列表
     */
    @RequestMapping(value = "/listPost")
    public void listPost(HttpServletResponse response,
                         Integer draw,
                         Integer start,
                         Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<Category> page = categoryService.findPage(1, 0, pageNum, length);
            List<PostBase> postBaseList;
            for (Category category : page.getContent()) {
                // 帖子分类下对应的帖子数量
                postBaseList = postBaseService.findByCategoryId(category.getId());
                category.setCount((long) (postBaseList != null ? postBaseList.size() : 0));
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 编辑保存帖子分类
     */
    @RequestMapping(value = "/editPost")
    @ResponseBody
    private Integer editPost(String name, Long categoryId) throws UnsupportedEncodingException {

        Category category;
        //String msg = request.getParameter("name");
        //String name = new String(msg.getBytes("ISO-8859-1"), "UTF-8");

        name = sensitiveWordsService.replaceWord(name);
        if (categoryId == null) {
            category = new Category();
            //category.setCreateDate(System.currentTimeMillis());
        } else {
            category = categoryService.queryByPK(categoryId);
        }
        category.setName(name);
        category.setType(Constant.CATEGORY_TYPE_001);
        category.setUpdateDate(System.currentTimeMillis());
        categoryService.save(category);

        return 1;
    }

    /**
     * 帖子下架、删除剧照音乐
     */
    @RequestMapping(value = "isDown")
    @ResponseBody
    private Integer isDown(Long categoryId, Integer status) {

        Category category = categoryService.queryByPK(categoryId);

        // 更新将该分类后的分类次序
        categoryService.updateShowTurn(category.getShowTurn());

        category.setStatus(status);
        category.setShowTurn(null);
        categoryService.save(category);

        //categoryService.delete(categoryService.queryByPK(categoryId));

        return 1;
    }

    /**
     * 剧照分类列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexStill")
    public String indexStill() {
        return "category/listStill";
    }

    /**
     * 查询剧照分类列表
     */
    @RequestMapping(value = "/listStill")
    public void listStill(HttpServletResponse response,
                          Integer draw,
                          Integer start,
                          Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<Category> page = categoryService.findPage(2, 0, pageNum, length);
            List<StillResource> stillResourceList;
            for (Category category : page.getContent()) {
                if (StringUtils.isNotEmpty(category.getUrl())) {
                    category.setUrl(ImageUtil.clearUploadUrl(category.getUrl()));
                }

                // 剧照分类下对应的剧照数量
                stillResourceList = stillService.findByCategoryId(category.getId());
                category.setCount((long) (stillResourceList != null ? stillResourceList.size() : 0));
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 编辑保存剧照分类
     */
    @RequestMapping(value = "/editStill")
    @ResponseBody
    public Integer editStill(HttpServletRequest request,
                             Long categoryId,
                             @RequestParam(value = "imageFile", required = false) MultipartFile file) throws IOException {

        Category category;
        String msg = request.getParameter("name");
        //String name = new String(msg.getBytes("ISO-8859-1"), "UTF-8");
        msg = sensitiveWordsService.replaceWord(msg);
        if (categoryId == null) {
            category = new Category();
            //category.setCreateDate(System.currentTimeMillis());
        } else {
            category = categoryService.queryByPK(categoryId);
        }
        category.setName(msg);
        category.setType(Constant.CATEGORY_TYPE_002);

        //MultipartFile multipartFile = file;
        if (null != file) {
            FileBo fileBo = FileUtil.save(file, true);
            category.setUrl(fileBo.getPath());
            category.setSuolue(fileBo.getSuoluePath());
        }

        category.setUpdateDate(System.currentTimeMillis());
        categoryService.save(category);

        return 1;
    }

    /**
     * 音乐分类列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/indexMusic")
    public String indexMusic() {
        return "category/listMusic";
    }

    /**
     * 查询音乐分类列表
     */
    @RequestMapping(value = "/listMusic")
    public void listMusic(HttpServletResponse response,
                          Integer draw,
                          Integer start,
                          Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<Category> page = categoryService.findPage(Constant.CATEGORY_TYPE_003, 0, pageNum, length);

            List<MusicResource> musicResourceList;
            for (Category category : page.getContent()) {
                if (StringUtils.isNotEmpty(category.getUrl())) {
                    category.setUrl(ImageUtil.clearUploadUrl(category.getUrl()));
                }

                // 音乐分类下对应音乐数量
                musicResourceList = musicService.findByCategoryId(category.getId());
                category.setCount((long) (musicResourceList != null ? musicResourceList.size() : 0));
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 编辑保存音乐分类
     */
    @RequestMapping(value = "/editMusic")
    @ResponseBody
    public Integer editMusic(HttpServletRequest request,
                             Long categoryId,
                             @RequestParam(value = "imageFile", required = false) MultipartFile file) throws IOException {

        Category category;
        String msg = request.getParameter("name");
        //String name = new String(msg.getBytes("ISO-8859-1"), "UTF-8");
        msg = sensitiveWordsService.replaceWord(msg);
        if (categoryId == null) {
            category = new Category();
            //category.setCreateDate(System.currentTimeMillis());
        } else {
            category = categoryService.queryByPK(categoryId);
        }
        category.setName(msg);
        category.setType(Constant.CATEGORY_TYPE_003);

        //MultipartFile multipartFile = file;
        if (null != file) {
            FileBo fileBo = FileUtil.save(file, true);
            category.setUrl(fileBo.getPath());
            category.setSuolue(fileBo.getSuoluePath());
        }

        category.setUpdateDate(System.currentTimeMillis());
        categoryService.save(category);

        return 1;
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @ResponseBody
    public Integer deleteBatch(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        for (Long id : arrayId) {
            /*Category category = categoryService.queryByPK(id);
            category.setStatus(1);
            categoryService.save(category);
            categoryService.update(category);*/

            categoryService.delete(categoryService.queryByPK(id));
        }
        return 1;
    }

    /**
     * 分类信息排序
     */
    @RequestMapping("/move")
    @ResponseBody
    public Integer move(Long categoryId, Integer turn) {
        try {
            return categoryService.changeShowTurn(categoryId, turn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
